/*
 * @Author: ZhuQiMing
 * @CreateTime: 2020/6/8 20:29
 */
import serviceUrl from "../utils/baseUrl";

const Fly = require("../lib/wx.umd.min.js");
const fly = new Fly();
// 默认请求配置
fly.config.timeout = 500000;
fly.config.headers["Content-Type"] = "application/json";
fly.config.baseURL = serviceUrl.API;

// 添加请求拦截器
fly.interceptors.request.use((request) => {
  // if (!request.body) {
  //     request.body = {}
  // }
  let _token = wx.getStorageSync("token");

  //if (loginInfo && request.url !== "/patient/auth/v1/wxauth") {
  if (_token) {
    request.headers["Authorization"] = `Bearer ${_token}`;
  }

  // console.log('request', request);
  // wx.showLoading({
  //   title: "加载中",
  //   mask: true,
  // });
  return request;
});
// 响应请求拦截器
fly.interceptors.response.use(
  (response) => {
    // wx.hideLoading();
    // console.log('success', response);
    if (response.data.code == 401) {
      wx.removeStorageSync("token");
      // 重新登录
      wx.navigateTo({
        url: "/pages/login/login",
      });
    } else if (response.data.code != 0) {
      wx.showToast({
        title: response.data.message,
        icon: "none",
      });
    }
    return response; // 请求成功之后将返回值返回
  },
  (err) => {
    // 请求出错，根据返回状态码判断出错原因
    // console.log('error', err)
    wx.hideLoading();
    wx.showToast({
      title: err.message,
      icon: "none",
    });
  }
);
export default fly;
